package com.biz.primus.ms.homepage.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.ms.homepage.dao.ro.ProgramRo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * 首页栏目redis dao
 */
@Repository
public class ProgramRedisDao extends CrudRedisDao<ProgramRo, Long> {

    /**
     * 保存首页栏目
     */
    @Override
    public void save(ProgramRo ro) {
        super.save(ro);
        super.zadd(getCoverProgramIdsSortedSetKey(ro.getCoverId()), ro.getCreateTimestamp(), ro.getId());
    }

    /**
     * 删除首页栏目
     */
    @Override
    public void delete(Long programId) {

        ProgramRo programRo = findOne(programId);
        super.delete(programId);
        if(programRo != null){
            super.zrem(getCoverProgramIdsSortedSetKey(programRo.getCoverId()), RedisUtil.toByteArray(programId));
        }
    }

    /**
     * 根据首页id删除其下所有栏目
     */
    public void deleteByCoverId(String coverId) {

        Set<byte[]> programIds = super.zangeByScore(getCoverProgramIdsSortedSetKey(coverId), "-inf", "+inf");
//        pipleDelete(getKeyListByIdSet(programIds)); //没有批量从ids sorted set key中移出的功能
        if(CollectionUtils.isEmpty(programIds)){
            return;
        }
        for (byte[] programId : programIds) {
            delete(RedisUtil.byteArrayToLong(programId));
        }
    }

    /**
     * 根据首页Id查找其所有栏目
     */
    public List<ProgramRo> findByCoverId(String coverId) {
        Set<byte[]> coverIdBytes = super.zangeByScore(getCoverProgramIdsSortedSetKey(coverId), "-inf", "+inf");
        return findByIds(coverIdBytes);
    }

    private String getCoverProgramIdsSortedSetKey(String coverId){
        return  super.getKeyByParams("cover_" + coverId + "_ids");
    }

}
